import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Drawer, Popconfirm } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CommonModal from './components/CommonModal';
import type { TableListItem } from './data.d';
import { queryBookList, updateBook, addBook, removeBookList, deleteBook } from './service';

/**
 * 添加书籍
 * @param fields
 */
const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');
  try {
    await addBook({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新书籍
 * @param fields
 */
const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在更新');
  try {
    await updateBook({ ...fields });
    hide();

    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeBookList({
      key: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const handleDelete = async (record: TableListItem) => {
  const hide = message.loading('正在删除');
  try {
    await deleteBook(record.id);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<TableListItem>();
  const [formInitVal, setFormInitVal] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  const columns: ProColumns<TableListItem>[] = [
    {
      title: "书籍主键id",
      dataIndex: 'id',
      tip: "书籍主键id",
      hideInForm: true,
      hideInTable: true,
      search: false,
    },
    {
      title: '书籍名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '书籍描述',
      dataIndex: 'description',
      valueType: 'textarea',
      ellipsis: true,
      search: false,
    },
    {
      title: '作者',
      dataIndex: 'author',
      valueType: 'text',
    },
    {
      title: '单价',
      dataIndex: 'price',
      search: false,
      renderText: (val: string) =>
        `${val}元`,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      search: false,
      hideInForm: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return defaultRender(item);
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              setFormInitVal(record);
              handleUpdateModalVisible(true);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <Popconfirm title="确认要删除吗？" onConfirm={() => {
            handleDelete(record).then(r => {
              if (r) {
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            });
          }}>
            <a href="#">
              删除
            </a>
          </Popconfirm>
          
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem>
        headerTitle="书籍列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params) => queryBookList({ ...params })}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
              <span>
                总计 {selectedRowsState.reduce((pre, item) => pre + item.price, 0)} 元
              </span>
            </div>
          }
        >
          <Popconfirm title="确认要删除吗？" onConfirm={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}>
            <Button              
            >
              批量删除
            </Button>
          </Popconfirm>          
        </FooterToolbar>
      )}
      <CommonModal onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible} title="新增书籍">
        <ProTable<TableListItem, TableListItem>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
        />
      </CommonModal>
      <CommonModal onCancel={() => handleUpdateModalVisible(false)} modalVisible={updateModalVisible} title="更新书籍">
        <ProTable<TableListItem, TableListItem>
          onSubmit={async (value) => {
            // 更新暂时手动设置id
            // id列在proTable中隐藏导致保存时传的值没有ID
            // TODO 后期切换成ProForm已支持更好的代码风格（现在不会😂）
            const param = {...value, id: formInitVal?.id as number};
            const success = await handleUpdate(param);
            if (success) {
              handleUpdateModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
          form={{initialValues: formInitVal}}
        />
      </CommonModal>
      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
